package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter("*.jsp")
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //login.jsp 要不要拦截？？？？ 不要，要放行
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();

        if (uri.endsWith("login.jsp") || uri.endsWith("loginStudentServlet")){
            //当前访问的是login.jsp页面，不需要拦截
            filterChain.doFilter(req,resp);
            return;
        }

        //判断是否登录
        Object user = req.getSession().getAttribute("user");
        if (user == null){ //没登陆
            //跳转到登录页面
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        }else{
            //登录,放行
            filterChain.doFilter(req,resp);
        }

    }

    @Override
    public void destroy() {

    }
}
